import { nextTick } from "../../src/util";

let has = {};
let queue = []; // 更新队列
let pending = false;

function flushSchedularQueue() {
  let i = 0;
  while (i < queue.length) {
    let watcher = queue[i];
    watcher.run();

    //  对于渲染 watcher 就默认执行一次
    if (!watcher.user) {
      watcher.cb();
    }
    i++;
  }

  // 此次更新完毕后就清空队列和缓存
  queue = [];
  has = {};
  pending = false;
}

// 每次数据更新都会进入此方法
export function queueWatcher(watcher) {
  // 更新时对 watcher 去重
  let id = watcher.id;
  if (has[id] == null) {
    queue.push(watcher);
    has[id] = true;
    // log("watcher---", watcher);
    // 异步批量更新，让同步代码先执行完，多次同步更新不同数据也只会执行一次
    // setTimeout(flushSchedularQueue,0) // nextTick 的最初版
    if (!pending) {
      nextTick(flushSchedularQueue);
      pending = true;
    }
  }
}
